/**
* <p>Title: TcpServer.java</p>
* <p>Copyright: Copyright (c) 2016</p>
* <p>Company: lty</p>
*/
package com.lty.bbapp.netty;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
* <p>Title: TcpServer</p>
* <p>Description: </p>
* <p>Company: lty</p>
* @author liuhao
* @date 2016年12月2日 下午5:40:27
* version 1.0
*/
import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.util.StringUtils;

import com.lty.bbapp.custom.DataHelper;
import com.lty.bbapp.instance.BusMap;
import com.lty.bbapp.instance.DevIdToVehicleId;
import com.lty.bbapp.instance.ErrVehicleIdsMap;
import com.lty.bbapp.instance.FilterLineIdsMap;
import com.lty.entity.Bus;
import com.lty.entity.ReversalCustom;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;

/***
 * 
 * <p>Title: TcpServer</p>
 * <p> Description: netty服务端启动类</p>
 * <p>Company: lty</p>
 * @author liuhao
 * @date 2016年12月13日 下午6:44:31 version 1.0
 */
public class TcpServer {

	private static final Logger logger = Logger.getLogger(TcpServer.class);
	// connect to server
	private String IP;

	private int PORT;

	public String getIP() {
		return IP;
	}

	public void setIP(String iP) {
		IP = iP;
	}

	public int getPORT() {
		return PORT;
	}

	public void setPORT(int pORT) {
		PORT = pORT;
	}

	/** 用于分配处理业务线程的线程组个数 */
	protected static final int BIZGROUPSIZE = Runtime.getRuntime().availableProcessors() * 2; // 默认
	/** 业务出现线程大小 */
	protected static final int BIZTHREADSIZE = 4;
	/*
	 * NioEventLoopGroup实际上就是个线程池,
	 * NioEventLoopGroup在后台启动了n个NioEventLoop来处理Channel事件,
	 * 每一个NioEventLoop负责处理m个Channel,
	 * NioEventLoopGroup从NioEventLoop数组里挨个取出NioEventLoop来处理Channel
	 */
	private static final EventLoopGroup bossGroup = new NioEventLoopGroup(BIZGROUPSIZE);
	private static final EventLoopGroup workerGroup = new NioEventLoopGroup(BIZTHREADSIZE);

	public void run() throws Exception {
		ServerBootstrap b = new ServerBootstrap();
		b.group(bossGroup, workerGroup);
		b.channel(NioServerSocketChannel.class);
		b.childHandler(new ChannelInitializer<SocketChannel>() {
			@Override
			public void initChannel(SocketChannel ch) throws Exception {
				ChannelPipeline pipeline = ch.pipeline();

				ByteBuf delimiter1 = Unpooled.copiedBuffer("*FH".getBytes());
				pipeline.addLast(new DelimiterBasedFrameDecoder(Integer.MAX_VALUE, delimiter1));

				pipeline.addLast("decoder", new MyNettyDecoder());
				pipeline.addLast(new TcpServerHandler());
			}
		});

		b.bind(IP, PORT).sync();
		logger.info("TCP服务器已启动");
	}

	protected void shutdown() {
		workerGroup.shutdownGracefully();
		bossGroup.shutdownGracefully();
	}

	public static ApplicationContext context = null;

	public static DataHelper dataHelper = null;
	public static ReversalCustom reversalCustom = null;

	public static BusMap busMap = BusMap.getInstance();
	public static FilterLineIdsMap filterLineIdsMap = FilterLineIdsMap.getInstance();
	public static ErrVehicleIdsMap errVehicleIdsMap = ErrVehicleIdsMap.getInstance();

	public static DevIdToVehicleId devIdToVehicleId = DevIdToVehicleId.getInstance();

	public static void initContext() {
		context = new ClassPathXmlApplicationContext("applicationContext.xml");
		dataHelper = (DataHelper) context.getBean("dataHelper");
		reversalCustom = (ReversalCustom) context.getBean("reversalCustom");
	}

	public static void selectAllBus() {
		initContext();

		List<Bus> list = dataHelper.getAllBuses();
		for (int i = 0; i < list.size(); i++) {
			Bus bus = list.get(i);
			String equiId = bus.getDevId();
			String lineId = bus.getLineId();
			String busName = bus.getBusName();

			busMap.put(equiId, Integer.valueOf(lineId));
			devIdToVehicleId.put(equiId, Integer.valueOf(busName));
		}
	}
	
	//需要反向的线路和车辆
	public static void prepareReversals(){
		List<String> lineIds = new ArrayList<>();
		List<String> vehicleNos = new ArrayList<>();
		
		String lineIdsStr = reversalCustom.getLineIds();
		String vehicleNosStr = reversalCustom.getVehicleNos();
		
		if(!StringUtils.isEmpty(lineIdsStr)){
			lineIds = Arrays.asList(lineIdsStr.split(","));
		}
		
		if(!StringUtils.isEmpty(vehicleNosStr)){
			vehicleNos = Arrays.asList(vehicleNosStr.split(","));
		}
		
		filterLineIdsMap.put("lineIds", lineIds);
		errVehicleIdsMap.put("vehicleNos", vehicleNos);
	}

	public static void main(String[] args) throws Exception {
		// 将设备id与lineId映射关系保存于StationMap
		selectAllBus();
		prepareReversals();

		logger.info("开始启动TCP服务器...");

		TcpServer tcpServer = (TcpServer) context.getBean("tcpServer");
		tcpServer.run();
	}

}
